require "stockpriceprovider/stockpriceprovider.rb"
require "net/ftp"

class BossaPl < StockPriceProvider

  @@bossapl = nil
  attr_accessor :data, :lastUpdate
  @@REFRESH_TIME = 60

  def BossaPl.create
    @@bossapl = new unless @@bossapl
    @@bossapl
  end


  def priceFor(stock)
    refresh
    tab = @data.select {|tab|
      tab.name == stock
    }
    tab[0].price
  end

  def stockValueFor(stock)
    refresh
    tab = @data.select {|tab|
      tab.name == stock
    }
    tab[0]
  end

  def online?
    begin
     ftp = Net::FTP.new('ftp.bossa.pl')
     true
    rescue StandardError => e
      false
    end
  end

  private
  def refresh
    if self.lastUpdate.to_i + @@REFRESH_TIME <= Time.now.to_i
      self.data = []
      ftp = Net::FTP.new('ftp.bossa.pl')
      ftp.login
      ftp.passive = true
      ftp.gettextfile("/pub/ciagle/mstock/sesjacgl/sesjacgl.prn") { |line|
        @data << Item.newItem(line.split(","))
      }
      ftp.close
      self.lastUpdate = Time.now
    end
  end

  class Item < StockValue
    attr_accessor :name, :date, :open, :max, :min, :price, :vol
    def self.newItem(arr)
      result = new()
      result.name = arr[0]
      result.date = arr[1]
      result.open = arr[2]
      result.max = arr[3]
      result.min = arr[4]
      result.price = arr[5]
      result.vol = arr[6]
      result
    end

    def getName
      self.name
    end
    def getPrice
      self.price
    end
    def getDate
      self.date
    end
  end

end